package com.freshmarket.freshmarket.realm;

import com.freshmarket.freshmarket.dao.AuthoMapper;
import com.freshmarket.freshmarket.entity.Manager;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
public class CustomRealm extends AuthorizingRealm {
    @Resource
    private AuthoMapper authoMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Manager user = (Manager) principalCollection.getPrimaryPrincipal();

        return null;

    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("当前用户为:{}"+(String)authenticationToken.getPrincipal());

        Manager manager = authoMapper.findByManagerName((String) authenticationToken.getPrincipal());
        if(manager == null){
            throw new UnknownAccountException("该用户不存在");
        }
        //System.out.println("hhh"+manager);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(manager, manager.getManagerPassword(), getName());
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("manager",manager);
        return simpleAuthenticationInfo;
    }
}
